<template>
  <div v-show="active === flag" class="step-main">
    <div class="step-content">
      <!-- 基础表单 -->
      <v-card class="rounded-lg elevation-10">
        <v-card-text class="pa-2">
          <v-form ref="baseFormRef" v-model="formValid">
            <v-row>
              <v-col cols="12" md="2">
                <v-text-field v-model="baseFormCurr.tableName" label="表名称" :rules="rules.tableName" required />
              </v-col>
              <v-col cols="12" md="2">
                <v-select v-model="baseFormCurr.tableType" :items="dictCurr.table_type" item-title="dictName"
                  item-value="dictValue" label="表类型" :disabled="formState.tableType" :rules="rules.tableType"
                  @update:model-value="tableTypeChange" />
              </v-col>
              <v-col cols="12" md="2">
                <v-text-field v-model="baseFormCurr.comments" label="描述" :rules="rules.comments" maxlength="100" counter
                  required />
              </v-col>
              <v-col cols="12" md="2">
                <v-select v-model="baseFormCurr.jdbcType" :items="dictCurr.jdbc_type" item-title="dictName"
                  item-value="dictValue" label="数据库类型" :disabled="formState.jdbcType" :rules="rules.jdbcType"
                  @update:model-value="jdbcTypeChange" />
              </v-col>
              <v-col cols="12" md="2">
                <v-text-field v-model="baseFormCurr.remark" label="备注" maxlength="120" counter />
              </v-col>
            </v-row>
          </v-form>
        </v-card-text>
      </v-card>

      <!-- 操作按钮 -->
      <v-card class=" rounded-lg elevation-10">
        <v-card-text class="pa-2">

          <v-btn :disabled="!baseFormCurr.jdbcType" color="primary" prepend-icon="mdi-plus" class="mr-2"
            @click="columnHandleAdd">
            添加
          </v-btn>
          <v-btn color="primary" prepend-icon="mdi-plus" class="mr-2" @click="dialogVisible = true">
            常用字段
          </v-btn>
          <v-btn :disabled="!selectRows.length" color="error" prepend-icon="mdi-delete" @click="columnHandleDelete">
            删除
          </v-btn>
        </v-card-text>
      </v-card>

      <!-- 字段表格 -->
      <v-card class="rounded-lg elevation-10">
        <v-data-table :items="tableFormCurr" :headers="headers" item-key="id" show-select show-headers
          :loading="loading" v-model="selectRows" class="field-table" no-data-text="暂无字段数据，请点击'添加'按钮添加字段"
          :items-per-page="-1" hide-default-footer>
          <template #item.drag="{ item }">
            <v-btn icon="mdi-drag" size="small" variant="text" class="move-btn" />
          </template>

          <template #item.fieldName="{ item, index }">
            <v-text-field v-model="item.fieldName" :disabled="item.disabled" :rules="columnRules.fieldName"
              variant="outlined" density="compact" hide-details="auto" />
          </template>

          <template #item.fieldType="{ item }">
            <v-autocomplete v-model="item.fieldType" :items="currentFieldTypes" class="rounded-lg" label="字段类型"
              variant="outlined" :search-input.sync="search" density="compact" hide-details="auto" />
          </template>

          <template #item.fieldLength="{ item }">
            <v-text-field v-model.number="item.fieldLength" type="number" :disabled="item.disabled" :min="0"
              :max="20000" variant="outlined" density="compact" hide-details="auto" />
          </template>

          <template #item.fieldPrecision="{ item }">
            <v-text-field v-model.number="item.fieldPrecision" type="number" :disabled="item.disabled" :min="0"
              :max="100" variant="outlined" density="compact" hide-details="auto" />
          </template>

          <template #item.fieldComments="{ item }">
            <v-text-field v-model="item.fieldComments" :disabled="item.disabled" :rules="columnRules.fieldComments"
              maxlength="100" counter variant="outlined" density="compact" hide-details="auto" />
          </template>

          <template #item.izPk="{ item }">
            <v-switch v-model="item.izPk" :disabled="item.disabled" :true-value="1" :false-value="0" color="primary"
              hide-details @update:model-value="pKChange(item)" />
          </template>

          <template #item.izNotNull="{ item }">
            <v-switch v-model="item.izNotNull" :disabled="item.disabled || item.izPk === 1" :true-value="1"
              :false-value="0" color="primary" hide-details />
          </template>
        </v-data-table>
      </v-card>
    </div>

    <!-- 步骤底部 -->
    <StepFooter ref="stepFooterRef" class="rounded-lg elevation-10 ma-2" :flag="flag" :info-data="{
      obj: this,
      baseForm: baseFormCurr,
      tableForm: tableFormCurr
    }" :max-flag="maxFlag" :min-flag="minFlag" />

    <!-- 选择预制字段弹窗 -->
    <v-dialog v-model="dialogVisible" max-width="600">
      <v-card>
        <v-card-title>选择常见字段</v-card-title>
        <v-card-text>
          <v-row>
            <v-col v-for="item in BuiltInFields" :key="item.fieldName" cols="12" sm="6" md="4">
              <v-checkbox v-model="BuiltInFieldsSelect" :value="item.fieldName" :label="item.fieldName" color="primary"
                @change="changeBuiltInFieldsSelect" />
            </v-col>
          </v-row>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="dialogVisible = false">取消</v-btn>
          <v-btn color="primary" @click="AddDefaultFields">确定</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue';
import { isCode, isNull, isNotNull } from '@/utils/validate';
import StepFooter from './footer/StepFooter.vue';
import { deepClone } from '@/utils/clone';
import { uuid } from '@/utils';
import { getFieldTypes, getJavaFieldTypesBySafety } from '@/api/generator/tableManagement';
import { message } from '@/utils/message';
import { getDictListSync } from '@/utils/dict';
import { $baseConfirm } from '@/utils/confirm';

interface Props {
  active: number;
  minFlag: number;
  maxFlag: number;
  baseForm: any;
  tableForm: any[];
  dict: any;
  baseDictData: any;
}

const props = withDefaults(defineProps<Props>(), {
  active: 1,
  minFlag: 1,
  maxFlag: 1,
  baseForm: () => ({}),
  tableForm: () => [],
  dict: () => ({}),
  baseDictData: () => ({ fieldList: [], JavaFieldMap: {} })
});
const search = ref('');

const emit = defineEmits(['inform-flag', 'inform-data', 'change-step', 'close', 'submit']);

// 表格头部定义
const headers = [
  { title: '拖动', key: 'drag', value: 'drag', width: 80, sortable: false },
  { title: '字段名称', key: 'fieldName', value: 'fieldName', width: 200 },
  { title: '字段类型', key: 'fieldType', value: 'fieldType', width: 180 },
  { title: '字段长度', key: 'fieldLength', value: 'fieldLength', width: 140 },
  { title: '字段精度', key: 'fieldPrecision', value: 'fieldPrecision', width: 140 },
  { title: '字段描述', key: 'fieldComments', value: 'fieldComments', width: 240 },
  { title: '主键', key: 'izPk', value: 'izPk', width: 80 },
  { title: '非空', key: 'izNotNull', value: 'izNotNull', width: 80 }
];

// 内置字段定义
const BuiltInFields = [
  {
    fieldName: "id",
    fieldType: "bigint",
    fieldLength: 19,
    fieldPrecision: 0,
    fieldComments: "唯一主键",
    izPk: 1,
    izNotNull: 1,
    javaType: "String",
    sort: 0,
    disabled: false
  },
  {
    fieldName: "org_ids",
    fieldType: "varchar",
    fieldLength: 500,
    fieldPrecision: 0,
    fieldComments: "父级主键集合",
    izPk: 0,
    izNotNull: 0,
    javaType: "String",
    sort: 1,
    disabled: false
  },
  {
    fieldName: "tenant_id",
    fieldType: "bigint",
    fieldLength: 19,
    fieldPrecision: 0,
    fieldComments: "多租户ID",
    izPk: 0,
    izNotNull: 0,
    javaType: "String",
    sort: 8,
    disabled: false
  },
  {
    fieldName: "create_by",
    fieldType: "bigint",
    fieldLength: 19,
    fieldPrecision: 0,
    fieldComments: "创建者",
    izPk: 0,
    izNotNull: 1,
    javaType: "String",
    sort: 10,
    disabled: false
  },
  {
    fieldName: "create_time",
    fieldType: "datetime",
    fieldLength: 0,
    fieldPrecision: 0,
    fieldComments: "创建时间",
    izPk: 0,
    izNotNull: 1,
    javaType: "String",
    sort: 11,
    disabled: false
  },
  {
    fieldName: "update_by",
    fieldType: "bigint",
    fieldLength: 19,
    fieldPrecision: 0,
    fieldComments: "修改人",
    izPk: 0,
    izNotNull: 1,
    javaType: "String",
    sort: 12,
    disabled: false
  },
  {
    fieldName: "update_time",
    fieldType: "datetime",
    fieldLength: 0,
    fieldPrecision: 0,
    fieldComments: "修改时间",
    izPk: 0,
    izNotNull: 1,
    javaType: "String",
    sort: 13,
    disabled: false
  },
  {
    fieldName: "deleted",
    fieldType: "int",
    fieldLength: 1,
    fieldPrecision: 0,
    fieldComments: "删除",
    izPk: 0,
    izNotNull: 1,
    javaType: "Integer",
    sort: 14,
    disabled: false
  },
  {
    fieldName: "version",
    fieldType: "int",
    fieldLength: 1,
    fieldPrecision: 0,
    fieldComments: "乐观锁",
    izPk: 0,
    izNotNull: 1,
    javaType: "Integer",
    sort: 15,
    disabled: false
  }
];

// 备用字段类型列表
const fallbackFieldTypes = [
  { title: 'varchar', value: 'varchar' },
  { title: 'int', value: 'int' },
  { title: 'bigint', value: 'bigint' },
  { title: 'decimal', value: 'decimal' },
  { title: 'datetime', value: 'datetime' },
  { title: 'date', value: 'date' },
  { title: 'text', value: 'text' },
  { title: 'char', value: 'char' },
  { title: 'tinyint', value: 'tinyint' },
  { title: 'smallint', value: 'smallint' },
  { title: 'mediumint', value: 'mediumint' },
  { title: 'float', value: 'float' },
  { title: 'double', value: 'double' },
  { title: 'timestamp', value: 'timestamp' },
  { title: 'time', value: 'time' },
  { title: 'year', value: 'year' },
  { title: 'blob', value: 'blob' },
  { title: 'longtext', value: 'longtext' }
];

// 响应式数据
const flag = ref(1);
const title = ref('数据库表设置');
const formValid = ref(false);
const loading = ref(false);
const dialogVisible = ref(false);
const BuiltInFieldsSelect = ref<string[]>([]);
const selectRows = ref<any[]>([]);
const baseFormRef = ref();
const stepFooterRef = ref();

const dictCurr = ref<any>({});
const baseFormCurr = ref<any>({});
const tableFormCurr = ref<any[]>([]);
const treeName = ref('parent_id');
const fieldTypeOptions = ref<any[]>([]);

const formState = reactive({
  jdbcType: false,
  tableType: false
});

// 新增字段模板
const columnFormTemp = ref({
  id: '',
  sort: 0,
  izPk: 0,
  izNotNull: 0,
  izShowList: 0,
  izShowForm: 0,
  queryType: '',
  fieldName: '',
  fieldType: '',
  fieldLength: 0,
  fieldPrecision: 0,
  fieldComments: '',
  javaType: '',
  validateType: '',
  showType: '',
  dictTypeCode: '',
  disabled: false
});

// 校验规则
const rules = {
  tableName: [
    (v: string) => !!v || '请输入表名',
    (v: string) => isCode(v) || '表名只能为字母、数字或下划线'
  ],
  tableType: [
    (v: string) => !!v || '请选择表类型'
  ],
  jdbcType: [
    (v: string) => !!v || '请选择数据库类型'
  ],
  comments: [
    (v: string) => !!v || '请输入描述'
  ]
};

const columnRules = {
  fieldName: [
    (v: string) => !!v || '请输入字段名称',
    (v: string) => isCode(v) || '字段名只能为字母、数字或下划线'
  ],
  fieldType: [
    (v: string) => !!v || '请选择字段类型'
  ],
  fieldComments: [
    (v: string) => !!v || '请输入字段描述'
  ]
};

// 计算属性：获取当前可用的字段类型选项
const currentFieldTypes = computed(() => {
  console.log('currentFieldTypes 计算属性执行');
  console.log('props.baseDictData?.fieldList:', props.baseDictData?.fieldList);
  console.log('fieldTypeOptions.value:', fieldTypeOptions.value);
  console.log('dictCurr.value.field_type:', dictCurr.value.field_type);

  // 第一优先级：使用 baseDictData.fieldList（这是从 API 获取的最新数据）
  if (props.baseDictData?.fieldList && Array.isArray(props.baseDictData.fieldList) && props.baseDictData.fieldList.length > 0) {
    console.log('使用baseDictData.fieldList:', props.baseDictData.fieldList);
    return props.baseDictData.fieldList.map((item: any) => ({
      title: item.dictName || item.label || item.text || item,
      value: item.dictValue || item.value || item
    }));
  }

  // 第二优先级：使用字典数据（jdbcType + '_data_type'）
  if (dictCurr.value.field_type && Array.isArray(dictCurr.value.field_type) && dictCurr.value.field_type.length > 0) {
    console.log('使用字典数据:', dictCurr.value.field_type);
    return dictCurr.value.field_type.map((item: any) => ({
      title: item.dictName || item.label || item.text || item,
      value: item.dictValue || item.value || item
    }));
  }

  // 第三优先级：使用从 API 获取的字段类型
  if (fieldTypeOptions.value && fieldTypeOptions.value.length > 0) {
    console.log('使用API数据:', fieldTypeOptions.value);
    return fieldTypeOptions.value.map((item: any) => ({
      title: item.dictName || item.label || item.text || item,
      value: item.dictValue || item.value || item
    }));
  }

  // 最后备用：返回备用字段类型
  console.log('使用备用字段类型');
  return fallbackFieldTypes;
});

// 获取字典列表的方法
function getDictList(typeCode: string) {
  return getDictListSync(typeCode);
}

// 数据库类型改变
function jdbcTypeChange(newValue: string) {
  console.log('jdbcType 改变为:', newValue);

  $baseConfirm('更换数据库类型将会清空当前已设字段，你确定要更换吗？', 'warning').then((result) => {
    if (result) {
      baseFormCurr.value.jdbcType = newValue;

      // 获取新的字段类型字典
      const dictKey = baseFormCurr.value.jdbcType + '_data_type';
      console.log('获取字典数据，key:', dictKey);

      const fieldTypes = getDictList(dictKey);
      console.log('获取到的字段类型:', fieldTypes);

      dictCurr.value.field_type = fieldTypes;
      tableFormCurr.value = [];
      doGetFieldData();
    } else {
      // 如果用户取消，需要恢复原值
      baseFormCurr.value.jdbcType = baseFormCurr.value.jdbcType;
    }
  });
}

// 表类型改变
function tableTypeChange(newValue: string) {
  if (newValue === '0') {
    // 删除 parent_id 字段
    for (let i = tableFormCurr.value.length - 1; i >= 0; i--) {
      const item = tableFormCurr.value[i];
      if (item.fieldName === treeName.value) {
        tableFormCurr.value.splice(i, 1);
        break;
      }
    }
  } else if (newValue === '1') {
    // 删除 parent_id 字段
    for (let i = tableFormCurr.value.length - 1; i >= 0; i--) {
      const item = tableFormCurr.value[i];
      if (item.fieldName === treeName.value) {
        tableFormCurr.value.splice(i, 1);
        break;
      }
    }

    // 增加 parent_id 字段
    const tmp = deepClone(columnFormTemp.value);
    tmp.disabled = true;
    tmp.fieldName = treeName.value;
    tmp.fieldType = 'bigint';
    tmp.fieldLength = 20;
    tmp.fieldComments = '上级ID';
    tmp.javaType = 'Integer';
    tmp.izNotNull = 1;
    columnHandleAdd(tmp);
  }
}

// 主键改变
function pKChange(el: any) {
  if (!isNull(el)) {
    if (el.izPk === 1) {
      el.izNotNull = 1;
    } else {
      el.izNotNull = 0;
    }
  }
}

// 获取字段数据
async function doGetFieldData() {
  loading.value = true;
  try {
    const fieldList = await doGetFieldTypes();
    const javaFieldMap = await doGetJavaFieldTypesBySafety();

    const fieldData = {
      fieldList: fieldList,
      JavaFieldMap: javaFieldMap
    };

    console.log('准备发送的字段数据:', fieldData);

    emit('inform-data', fieldData);
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

// 获取数据类型
async function doGetFieldTypes() {
  try {
    const { data } = await getFieldTypes();
    const fieldList = isNotNull(data) ? data : [];
    fieldTypeOptions.value = fieldList;
    return fieldList;
  } catch (error) {
    fieldTypeOptions.value = [];
    return [];
  }
}

// 获取 Java 类型
async function doGetJavaFieldTypesBySafety() {
  try {
    const { data } = await getJavaFieldTypesBySafety();

    const javaFieldMap = isNotNull(data) ? data : {};

    return javaFieldMap;
  } catch (error) {
    console.error('获取Java类型数据失败:', error);
    return {};
  }
}

// 添加字段
function columnHandleAdd(params?: any) {
  let temp;
  if (!isNull(params) && !(params instanceof MouseEvent)) {
    temp = params;
  } else {
    temp = deepClone(columnFormTemp.value);
  }

  temp.id = 'temp_' + uuid();
  if (!tableFormCurr.value || tableFormCurr.value.length === 0) {
    temp.sort = 0;
  } else {
    temp.sort = tableFormCurr.value.length;
  }
  tableFormCurr.value.push(temp);
}

// 删除字段
function columnHandleDelete() {
  if (selectRows.value.length > 0) {

    $baseConfirm('你确定要删除选中的字段吗？', 'warning').then((result) => {
      if (result) {
        // 获取选中行的 id 数组
        const selectedIds = selectRows.value.map((item) => {
          // 确保获取正确的 id，可能是 item 本身的 id 或者 item.id
          return item.id || item;
        });

        // console.log('要删除的 IDs:', selectedIds);

        // 从后往前删除，避免索引变化
        for (let i = tableFormCurr.value.length - 1; i >= 0; i--) {
          const item = tableFormCurr.value[i];

          // 检查当前项是否在选中列表中
          if (selectedIds.includes(item.id)) {
            // 如果是树形表格（tableType === '1'），不允许删除 parent_id 字段
            if (baseFormCurr.value.tableType === '1' && item.fieldName === treeName.value) {
              console.log(`跳过删除 ${treeName.value} 字段，因为是树形表格必需字段`);
              continue;
            }

            console.log(`删除字段: ${item.fieldName} (id: ${item.id})`);
            tableFormCurr.value.splice(i, 1);
          }
        }

        // 清空选中状态
        selectRows.value = [];

        message.success(`成功删除 ${selectedIds.length} 个字段`);
      }
    });
  } else {
    message.error('未选中任何行');
  }
}

// 内置字段选择变化
function changeBuiltInFieldsSelect() {
  BuiltInFieldsSelect.value = removeElementsFromArray(BuiltInFieldsSelect.value, tableFormCurr.value);
}

// 移除已存在的字段
function removeElementsFromArray(A: string[], B: any[]): string[] {
  return A.filter(a => {
    const isEqual = B.some(b => b.fieldName === a);
    if (isEqual) {
      message.error(`已存在字段：${a}`);
    }
    return !isEqual;
  });
}

// 添加默认字段
function AddDefaultFields() {
  for (const fieldName of BuiltInFieldsSelect.value) {
    AddDefaultFields2(fieldName);
  }
  dialogVisible.value = false;
  BuiltInFieldsSelect.value = [];
}

// 添加单个默认字段
function AddDefaultFields2(fieldName: string) {
  const temp = BuiltInFields.find(field => field.fieldName === fieldName);
  if (temp) {
    const newField = { ...temp, id: 'temp_' + uuid(), sort: tableFormCurr.value.length };
    tableFormCurr.value.push(newField);
  }
}

// 监听 props 变化
watch(() => props.baseForm, (newV) => {
  baseFormCurr.value = deepClone(newV);
}, { deep: true });

watch(() => props.tableForm, (newV) => {
  // 确保 tableForm 始终是数组
  tableFormCurr.value = Array.isArray(newV) ? deepClone(newV) : [];
}, { deep: true });

watch(() => props.dict, (newV) => {
  dictCurr.value = deepClone(newV);
  dictCurr.value.field_type = getDictList(baseFormCurr.value.jdbcType + '_data_type');
}, { deep: true });

// 组件挂载时执行
onMounted(() => {
  console.log('TableDataStep 组件挂载');

  // 告诉父节点自己的 flag 编号
  emit('inform-flag', flag.value, title.value);

  // 拷贝 props，确保 tableForm 是数组
  baseFormCurr.value = deepClone(props.baseForm);
  tableFormCurr.value = Array.isArray(props.tableForm) ? deepClone(props.tableForm) : [];
  dictCurr.value = deepClone(props.dict);

  console.log('初始化数据:');
  console.log('baseFormCurr:', baseFormCurr.value);
  console.log('dictCurr:', dictCurr.value);
  console.log('props.baseDictData:', props.baseDictData);

  // 数据库字段类型 - 如果有 jdbcType 则获取对应的字段类型
  if (baseFormCurr.value.jdbcType) {
    const dictKey = baseFormCurr.value.jdbcType + '_data_type';
    console.log('初始化时获取字典数据，key:', dictKey);

    const fieldTypes = getDictList(dictKey);
    console.log('初始化时获取到的字段类型:', fieldTypes);

    dictCurr.value.field_type = fieldTypes;
  }

  // 初始化数据
  doGetFieldData();
});
</script>

<style lang="scss">
.step-main {
  .step-content {
    height: 540px;
    overflow-y: auto;
  }

  .field-table {
    .v-data-table__tbody tr {
      &:hover {
        background-color: rgba(0, 0, 0, 0.04);
      }
    }
  }

  .move-btn {
    cursor: grab;

    &:active {
      cursor: grabbing;
    }
  }
}
</style>
